<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function concurRequest(urls, maxNum) {
        return new Promise((resolve) => {
          // urls为空
          if (!urls.length) {
            resolve([]);
          }
          const results = [];
          // 下一个请求的下标
          let index = 0;
          // 完成请求的数量
          let count = 0;
          // 发送请求
          async function request() {
            // 防止无休止的发请求,因为请求是异步的
            if (index === urls.length) {
              return;
            }
            const i = index;
            const url = urls[index];
            index++;
            console.log(url);
            try {
              const resp = await fetch(url);
              results[i] = resp;
            } catch (error) {
              console
              results[i] = error;
            } finally {
              count++;
              // 判断是否所有的请求都已经完成
              if (count === urls.length) {
                resolve(results);
              }
              request();
            }
          }
          const times = Math.min(maxNum, urls.length);
          for (let i = 0; i < times; i++) {
            request();
          }
        });
      }

      const urls = [];
      for (let i = 0; i < 10; i++) {
        urls.push("https://dingweiquan.com" + i);
      }
      concurRequest(urls, 3).then((res) => {
        console.log(res);
      });
    </script>
  </body>
</html>
